/* soft_timer.c/h  3.0 */

#include "soft_timer.h"
#include "stdio.h"
#include "main.h"
volatile size_t tickCnt = 0;
static softTimer timer[TIMER_NUM];

void TIM0_CB(void *argv, uint16_t argc)
{
	HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_2);
}
void TIM1_CB(void *argv, uint16_t argc)
{

}
void TIM2_CB(void *argv, uint16_t argc)
{

}
void TIM3_CB(void *argv, uint16_t argc)
{

}

void tickCnt_Update(void)
{
	tickCnt++;
}

uint32_t tickCnt_Get(void)
{
	return tickCnt;
}

void softTimer_Init(void)
{
	uint16_t i;

	for (i = 0; i < TIMER_NUM; i++) {
		timer[i].state = SOFT_TIMER_STOPPED;
		timer[i].mode = MODE_ONE_SHOT;
		timer[i].match = 0;
		timer[i].period = 0;
		timer[i].cb = NULL;
		timer[i].argv = NULL;
		timer[i].argc = 0;
	}
}

uint8_t softTimer_GetState(uint16_t id)
{
	return timer[id].state;
}

void softTimer_Start(uint16_t id, tmrMode mode, uint32_t delay, callback *cb, void *argv, uint16_t argc)
{
	assert_param(id < TIMER_NUM);
	assert_param(mode == MODE_ONE_SHOT || mode == MODE_PERIODIC);

	timer[id].match = tickCnt_Get() + delay;
	timer[id].period = delay;
	timer[id].state = SOFT_TIMER_RUNNING;
	timer[id].mode = mode;
	timer[id].cb = cb;
	timer[id].argv = argv;
	timer[id].argc = argc;
}

void softTimer_Stop(uint16_t id)
{
	assert_param(id < TIMER_NUM);
	timer[id].state = SOFT_TIMER_STOPPED;
}

void softTimer_Update(void)
{
	uint16_t i;
	for (i = 0; i < TIMER_NUM; i++) {
		switch (timer[i].state) {
			case SOFT_TIMER_STOPPED:
			break;

			case SOFT_TIMER_RUNNING:
				if (timer[i].match <= tickCnt_Get()) {
					timer[i].state = SOFT_TIMER_TIMEOUT;
					timer[i].cb(timer[i].argv, timer[i].argc);
				}
			break;

			case SOFT_TIMER_TIMEOUT:
				if (timer[i].mode == MODE_ONE_SHOT) {
					timer[i].state = SOFT_TIMER_STOPPED;
				} else {
					timer[i].match = tickCnt_Get() + timer[i].period;
					timer[i].state = SOFT_TIMER_RUNNING;
				}
			break;

			default:
				//			printf("timer[%d] state error!\r\n", i);
			break;
		}
	}
}
